import '@wangeditor/editor/dist/css/style.css'; // 引入 css

import { IDomEditor } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';

import { commonUploadApi } from '@/api/common';

export interface EditorProps {
	value?: string;
	onChange?: (...args: any[]) => void;
}
function MyEditor({ value, onChange }: EditorProps) {
	// editor 实例
	const [editor, setEditor] = useState<IDomEditor | null>(null);
	// 编辑器内容
	const [html, setHtml] = useState('');

	// 模拟 ajax 请求，异步设置 html
	useEffect(() => {
		if (value) {
			setHtml(value ?? '');
		}
	}, [value]);

	// 工具栏配置
	const toolbarConfig = {};

	// 编辑器配置
	const editorConfig = {
		placeholder: '请输入内容...',
		MENU_CONF: {
			uploadImage: {
				customUpload: async (file: any, insertFn: any) => {
					const formData = new FormData();
					formData.append('file', file);
					const result = await commonUploadApi(formData);
					insertFn(result.data, '', result.data);
				}
			},
			uploadVideo: {
				customUpload: async (file: any, insertFn: any) => {
					const formData = new FormData();
					formData.append('file', file);
					const result = await commonUploadApi(formData);
					insertFn(result.data, '', result.data);
				}
			}
		}
	};
	// 及时销毁 editor ，重要！
	useEffect(() => {
		return () => {
			if (!editor) return;
			if (editor?.destroy) {
				editor.destroy();
			}
			setEditor(null);
		};
	}, []);
	const onChangeHandler = (editor: IDomEditor) => {
		const valueHtml = editor.getHtml();
		setHtml(valueHtml);
		if (onChange) {
			onChange(valueHtml);
		}
	};
	return (
		<div style={{ border: '1px solid #ccc', zIndex: 100 }}>
			<Toolbar
				editor={editor}
				defaultConfig={toolbarConfig}
				mode="default"
				style={{ borderBottom: '1px solid #ccc' }}
			/>
			<Editor
				defaultConfig={editorConfig}
				value={html}
				onCreated={setEditor}
				onChange={editor => onChangeHandler(editor)}
				mode="default"
				style={{ minHeight: '400px', overflowY: 'hidden' }}
			/>
		</div>
	);
}

export default MyEditor;
